package svc

import (
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/config"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc/modules"
	"go-zero-admin/apps/modules/iot/model"
	userClient "go-zero-admin/apps/system/cmd/rpc/client/user"
	userScopeClient "go-zero-admin/apps/system/cmd/rpc/client/userscope"

	natsio "github.com/nats-io/nats.go"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config config.Config
	// modules
	NatsConn   *natsio.Conn
	NatsJsConn natsio.JetStreamContext
	NatsEnConn *natsio.EncodedConn
	// rpc
	UserRpc      userClient.User
	UserScopeRpc userScopeClient.UserScope
	// model
	IotNetworkModel model.IotNetworkModel
	IotGatewayModel model.IotGatewayModel
	IotProductModel model.IotProductModel
	IotDeviceModel  model.IotDeviceModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	conn := sqlx.NewMysql(c.DB.DataSource)
	// 网络组件model
	iotNetworkModel := model.NewIotNetworkModel(conn, c.ModelCache)
	// 设备网关model
	iotGatewayModel := model.NewIotGatewayModel(conn, c.ModelCache)
	// 初始化link
	modules.NewLinkServer(iotNetworkModel)
	// 初始化nats
	cn, js, en := modules.NewNatsServer(c)
	return &ServiceContext{
		Config: c,
		// modules
		NatsConn:   cn,
		NatsJsConn: js,
		NatsEnConn: en,
		// rpc
		UserRpc:      userClient.NewUser(zrpc.MustNewClient(c.SystemRpc)),
		UserScopeRpc: userScopeClient.NewUserScope(zrpc.MustNewClient(c.SystemRpc)),
		// model
		IotNetworkModel: iotNetworkModel,
		IotGatewayModel: iotGatewayModel,
		IotProductModel: model.NewIotProductModel(conn, c.ModelCache),
		IotDeviceModel:  model.NewIotDeviceModel(conn, c.ModelCache),
	}
}
